<!--
  编辑器工具栏组件
  包含保存、撤销、重做、导出等功能
-->
<template>
  <div class="editor-toolbar">
    <!-- 左侧工具组 -->
    <div class="toolbar-group left">
      <n-button-group>
        <n-button 
          secondary 
          @click="$emit('save')"
          :loading="saving"
        >
          <template #icon>
            <n-icon><SaveOutline /></n-icon>
          </template>
          保存
        </n-button>
        
        <n-button 
          secondary 
          @click="$emit('undo')"
          :disabled="!canUndo"
        >
          <template #icon>
            <n-icon><ArrowUndoOutline /></n-icon>
          </template>
          撤销
        </n-button>
        
        <n-button 
          secondary 
          @click="$emit('redo')"
          :disabled="!canRedo"
        >
          <template #icon>
            <n-icon><ArrowRedoOutline /></n-icon>
          </template>
          重做
        </n-button>
      </n-button-group>
      
      <n-divider vertical />
      
      <!-- 编辑工具 -->
      <n-button-group>
        <n-button 
          secondary 
          @click="handleCopy"
          :disabled="!hasSelection"
        >
          <template #icon>
            <n-icon><CopyOutline /></n-icon>
          </template>
          复制
        </n-button>
        
        <n-button 
          secondary 
          @click="handlePaste"
          :disabled="!canPaste"
        >
          <template #icon>
            <n-icon><ClipboardOutline /></n-icon>
          </template>
          粘贴
        </n-button>
        
        <n-button 
          secondary 
          @click="handleDelete"
          :disabled="!hasSelection"
        >
          <template #icon>
            <n-icon><TrashOutline /></n-icon>
          </template>
          删除
        </n-button>
      </n-button-group>
    </div>
    
    <!-- 中央工具组 -->
    <div class="toolbar-group center">
      <!-- 视图控制 -->
      <n-space>
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button 
              quaternary 
              circle 
              @click="toggleGrid"
              :type="showGrid ? 'primary' : 'default'"
            >
              <template #icon>
                <n-icon><GridOutline /></n-icon>
              </template>
            </n-button>
          </template>
          {{ showGrid ? '隐藏网格' : '显示网格' }}
        </n-tooltip>
        
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button
              quaternary
              circle
              @click="toggleSnap"
              :type="snapToGrid ? 'primary' : 'default'"
            >
              <template #icon>
                <n-icon><MagnetOutline /></n-icon>
              </template>
            </n-button>
          </template>
          {{ snapToGrid ? '关闭吸附' : '开启吸附' }}
        </n-tooltip>

        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button
              quaternary
              circle
              @click="toggleRenderMode"
              :type="isRealTimeRender ? 'primary' : 'default'"
            >
              <template #icon>
                <n-icon>
                  <PlayOutline v-if="isRealTimeRender" />
                  <PauseOutline v-else />
                </n-icon>
              </template>
            </n-button>
          </template>
          {{ isRealTimeRender ? '实时渲染' : '静态渲染' }}
        </n-tooltip>

        <n-divider vertical />
        
        <!-- 缩放控制 -->
        <n-button-group size="small">
          <n-button quaternary @click="zoomOut">
            <template #icon>
              <n-icon><RemoveOutline /></n-icon>
            </template>
          </n-button>
          
          <n-button quaternary @click="resetZoom">
            {{ Math.round(zoom * 100) }}%
          </n-button>
          
          <n-button quaternary @click="zoomIn">
            <template #icon>
              <n-icon><AddOutline /></n-icon>
            </template>
          </n-button>
        </n-button-group>
        
        <n-button quaternary @click="fitToScreen">
          <template #icon>
            <n-icon><ScanOutline /></n-icon>
          </template>
          适应屏幕
        </n-button>
      </n-space>
    </div>
    
    <!-- 右侧工具组 -->
    <div class="toolbar-group right">
      <n-space>
        <!-- 项目信息 -->
        <div class="project-info" v-if="currentProject">
          <n-text depth="3">{{ currentProject.name }}</n-text>
          <n-tag v-if="projectModified" type="warning" size="small">未保存</n-tag>
        </div>
        
        <n-divider vertical />
        
        <!-- 导出按钮 -->
        <n-button
          type="primary"
          @click="$emit('export')"
        >
          <template #icon>
            <n-icon><ShareOutline /></n-icon>
          </template>
          导出
        </n-button>

        <!-- 顶部工具栏抽屉切换按钮 -->
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button
              quaternary
              circle
              @click="$emit('toggle-header-drawer')"
              :type="headerDrawerVisible ? 'primary' : 'default'"
            >
              <template #icon>
                <n-icon><MenuOutline /></n-icon>
              </template>
            </n-button>
          </template>
          {{ headerDrawerVisible ? '隐藏顶部工具栏' : '显示顶部工具栏' }}
        </n-tooltip>

        <!-- 设置菜单 -->
        <n-dropdown
          :options="settingsOptions"
          @select="handleSettingsSelect"
        >
          <n-button quaternary circle>
            <template #icon>
              <n-icon><SettingsOutline /></n-icon>
            </template>
          </n-button>
        </n-dropdown>
      </n-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, h } from 'vue'
import { 
  NButton, 
  NButtonGroup, 
  NIcon, 
  NSpace, 
  NDivider, 
  NTooltip,
  NText,
  NTag,
  NDropdown
} from 'naive-ui'
import {
  SaveOutline,
  ArrowUndoOutline,
  ArrowRedoOutline,
  CopyOutline,
  ClipboardOutline,
  TrashOutline,
  GridOutline,
  MagnetOutline,
  RemoveOutline,
  AddOutline,
  ScanOutline,
  ShareOutline,
  SettingsOutline,
  PlayOutline,
  PauseOutline,
  MenuOutline
} from '@vicons/ionicons5'
import { useEditorStore } from '../../stores/editor'
import { message } from '../../utils/message'

// 属性定义
defineProps({
  headerDrawerVisible: {
    type: Boolean,
    default: false
  }
})

// 事件定义
defineEmits(['save', 'export', 'undo', 'redo', 'toggle-render-mode', 'toggle-header-drawer'])

// 状态管理
const editorStore = useEditorStore()

// 本地状态
const saving = ref(false)
const clipboard = ref<any>(null)

// 计算属性
const currentProject = computed(() => editorStore.currentProject)
const projectModified = computed(() => editorStore.projectModified)
const canUndo = computed(() => editorStore.history.canUndo)
const canRedo = computed(() => editorStore.history.canRedo)
const hasSelection = computed(() => 
  editorStore.selection.selectedLayers.length > 0 ||
  editorStore.selection.selectedTracks.length > 0 ||
  editorStore.selection.selectedKeyframes.length > 0
)
const canPaste = computed(() => clipboard.value !== null)
const showGrid = computed(() => editorStore.showGrid)
const snapToGrid = computed(() => editorStore.snapToGrid)
const zoom = computed(() => editorStore.viewport.zoom)
const isRealTimeRender = computed(() => editorStore.isRealTimeRender)

// 设置菜单选项
const settingsOptions = [
  {
    label: '项目设置',
    key: 'project-settings',
    icon: () => h(NIcon, null, { default: () => h(SettingsOutline) })
  },
  {
    label: '编辑器偏好',
    key: 'editor-preferences',
    icon: () => h(NIcon, null, { default: () => h(SettingsOutline) })
  },
  {
    type: 'divider',
    key: 'd1'
  },
  {
    label: '键盘快捷键',
    key: 'shortcuts',
    icon: () => h(NIcon, null, { default: () => h(SettingsOutline) })
  },
  {
    label: '关于',
    key: 'about',
    icon: () => h(NIcon, null, { default: () => h(SettingsOutline) })
  }
]

// 编辑操作
const handleCopy = () => {
  const selectedLayers = editorStore.layers.filter(layer => 
    editorStore.selection.selectedLayers.includes(layer.id)
  )
  
  if (selectedLayers.length > 0) {
    clipboard.value = {
      type: 'layers',
      data: JSON.parse(JSON.stringify(selectedLayers))
    }
    message.success(`已复制 ${selectedLayers.length} 个图层`)
  }
}

const handlePaste = () => {
  if (!clipboard.value) return
  
  if (clipboard.value.type === 'layers') {
    const layers = clipboard.value.data
    const newLayerIds: string[] = []
    
    layers.forEach((layer: any, index: number) => {
      const newLayer = editorStore.addLayer({
        ...layer,
        name: `${layer.name} 副本`,
        position: {
          x: layer.position.x + 20,
          y: layer.position.y + 20
        }
      })
      newLayerIds.push(newLayer.id)
    })
    
    // 选择新粘贴的图层
    editorStore.clearSelection()
    newLayerIds.forEach(id => editorStore.selectLayer(id, true))
    
    message.success(`已粘贴 ${layers.length} 个图层`)
  }
}

const handleDelete = () => {
  const selectedLayers = editorStore.selection.selectedLayers
  const selectedTracks = editorStore.selection.selectedTracks
  const selectedKeyframes = editorStore.selection.selectedKeyframes
  
  // 删除选中的图层
  selectedLayers.forEach(layerId => {
    editorStore.removeLayer(layerId)
  })
  
  // 删除选中的轨道
  selectedTracks.forEach(trackId => {
    editorStore.removeTrack(trackId)
  })
  
  // 删除选中的关键帧
  selectedKeyframes.forEach(keyframeId => {
    // 找到包含该关键帧的轨道
    for (const track of editorStore.tracks) {
      if (track.keyframes.some(kf => kf.id === keyframeId)) {
        editorStore.removeKeyframe(track.id, keyframeId)
        break
      }
    }
  })
  
  const totalDeleted = selectedLayers.length + selectedTracks.length + selectedKeyframes.length
  if (totalDeleted > 0) {
    message.success(`已删除 ${totalDeleted} 个项目`)
  }
}

// 视图控制
const toggleGrid = () => {
  editorStore.showGrid = !editorStore.showGrid
}

const toggleSnap = () => {
  editorStore.snapToGrid = !editorStore.snapToGrid
}

const toggleRenderMode = () => {
  editorStore.isRealTimeRender = !editorStore.isRealTimeRender
  // 通知画布组件切换渲染模式
  // 这里我们需要通过事件来通知父组件
}

const zoomIn = () => {
  const newZoom = Math.min(5, editorStore.viewport.zoom * 1.2)
  editorStore.viewport.zoom = newZoom
}

const zoomOut = () => {
  const newZoom = Math.max(0.1, editorStore.viewport.zoom / 1.2)
  editorStore.viewport.zoom = newZoom
}

const resetZoom = () => {
  editorStore.viewport.zoom = 1.0
  editorStore.viewport.panX = 0
  editorStore.viewport.panY = 0
}

const fitToScreen = () => {
  // TODO: 实现适应屏幕功能
  message.info('适应屏幕功能开发中...')
}

// 设置菜单处理
const handleSettingsSelect = (key: string) => {
  switch (key) {
    case 'project-settings':
      message.info('项目设置功能开发中...')
      break
    case 'editor-preferences':
      message.info('编辑器偏好功能开发中...')
      break
    case 'shortcuts':
      message.info('快捷键帮助功能开发中...')
      break
    case 'about':
      message.info('关于对话框功能开发中...')
      break
  }
}
</script>

<style lang="scss" scoped>
.editor-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  background-color: var(--card-color);
  border-bottom: 1px solid var(--border-color);
  min-height: 48px;
  
  .toolbar-group {
    display: flex;
    align-items: center;
    gap: 8px;
    
    &.center {
      flex: 1;
      justify-content: center;
    }
    
    &.right {
      justify-content: flex-end;
    }
  }
  
  .project-info {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
  }
}
</style>
